import { ElLoadingService, ElMessage, ElMessageBox, dayjs as _dayjs } from 'element-plus';
import config from '../../project.config';
import { isPlainObject } from './looseEqual';

import 'element-plus/es/components/loading/style/css';
import 'element-plus/es/components/message-box/style/css';
import 'element-plus/es/components/message/style/css';

export const development = import.meta.env.DEV;

export const projectConfig = config;

export const message = ElMessage;

export const dayjs = _dayjs;

export const sleep = (delaytime = 0) => new Promise((resolve) => setTimeout(resolve, delaytime));

export const remove = (arr: any[], el: any) => {
  const i = arr.indexOf(el);
  if (i > -1) {
    arr.splice(i, 1);
  }
};

export const confirm = async (content, options = {}) => {
  const { title = '温馨提示', type = 'warning', showCancelButton = true, useHtml } = options as any;
  await ElMessageBox.confirm(content, title, {
    type,
    showCancelButton,
    dangerouslyUseHTMLString: !!useHtml,
    center: true,
    draggable: true,
  });
};

let loadingInstance: any;
const loadingOptions = { lock: true, background: 'rgba(0, 0, 0, 0.5)' };

export const loading = {
  open: () => (loadingInstance = ElLoadingService(loadingOptions)),
  close: () => loadingInstance && loadingInstance.close(),
};

export const renderData = (data, ...args) => {
  if (typeof data === 'function') {
    return data(...args);
  }
  return data;
};

export const trimStringOfObject = (object) => {
  if (!isPlainObject(object)) return;
  for (const key in object) {
    if (Object.prototype.hasOwnProperty.call(object, key)) {
      const element = object[key];
      if (typeof element === 'string') {
        object[key] = element.trim();
      }
    }
  }
};

export const imageToBase64 = (imgUrl: string, ext = 'png') => {
  return new Promise<string>((reslove, reject) => {
    try {
      let canvas: any = document.createElement('canvas');
      const ctx: any = canvas.getContext('2d');
      const img = new Image();
      img.crossOrigin = 'Anonymous';
      img.onload = () => {
        canvas.height = img.height;
        canvas.width = img.width;
        ctx.drawImage(img, 0, 0);
        reslove(canvas.toDataURL(`image/${ext}`));
        canvas = null;
      };
      img.onerror = (e) => {
        console.log(e);
        reject(e);
      };
      img.src = imgUrl;
    } catch (e) {
      console.log(e);
      reject(e);
    }
  });
};
